package com.lyl.pipeline.utils;

import com.lyl.pipeline.annotation.PipeNode;
import com.lyl.pipeline.exception.PipelineException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Mr.Luo
 * @date 2022-08-08 14:34
 * @desc 节点处理工具类
 */
@Slf4j
public class PipeNodeUtil {

    /**
     * 获取SafeNode中的参数map
     *
     * @param pipeNode pipeNode
     * @return paramMap
     */
    public static Map<String, Object> getParamMap(PipeNode pipeNode) {
        Map<String, Object> map;
        try {
            map = Arrays.stream(pipeNode.params())
                    .map(t -> t.split(":|="))
                    .collect(Collectors.toMap(t -> t[0].trim(), t -> t[1].trim()));
        } catch (Exception e) {
            log.error("PipeNode自定义参数[{}]解析错误", Arrays.toString(pipeNode.params()), e);
            throw new PipelineException("PipeNode自定义参数params解析错误", e);
        }
        return map;
    }

    public static String getIp(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("x-forwarded-for");

        if (!checkIp(ip)) {
            if (!checkIp(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (!checkIp(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (!checkIp(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (!checkIp(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (!checkIp(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    private static boolean checkIp(String ip) {
        return !(ip == null || ip.length() == 0
                || "unknown".equalsIgnoreCase(ip));
    }

}
